package jmine.tec.database.pack.services;

import java.io.Serializable;

import jmine.tec.database.pack.PackException;

import org.hibernate.SessionFactory;

import bancosys.tec.persist.Persistable;
import bancosys.tec.persist.dao.BaseDAO;
import bancosys.tec.persist.dao.BaseDAOFactory;
import bancosys.tec.persist.dao.BeanNotFoundException;

/**
 * Implementação de PackEntityServiceHelper que não faz find. Deve ser utilizado na configuração de refdb para evitar que ocorra
 * substituição não intencional de registros que por acaso entrem com a mesma PK.
 * 
 * @author lundberg
 */
public class NkPackEntityServiceHelper implements PackEntityPersistenceHelper {

    private SessionFactory sessionFactory;

    private BaseDAOFactory daoFactory;

    /**
     * {@inheritDoc}
     */
    public <T extends Persistable> T findOrCreate(Class<T> entityClass, Serializable pk, String naturalKey) throws PackException {
        BaseDAO<T> dao = this.daoFactory.getGenericDAO(entityClass);
        if (naturalKey != null) {
            try {
                return dao.findByNaturalKey(naturalKey);
            } catch (BeanNotFoundException e) {
                // OK
            }
        }
        return dao.createBean();
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("deprecation")
    public <T extends Persistable> void save(T entity, Serializable pk) {
        if (pk != null && entity.getPk() == null) {
            this.sessionFactory.getCurrentSession().save(entity, pk);
        }
        entity.getPersister().save();
    }

    /**
     * @param daoFactory the daoFactory to set
     */
    public void setDaoFactory(BaseDAOFactory daoFactory) {
        this.daoFactory = daoFactory;
    }

    /**
     * @param sessionFactory the sessionFactory to set
     */
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
}
